<?php

/*

Desktopd Picture Server
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

@kind entry
@comment Unless specified, @kind defaults to 'class'

*/


namespace Desktopd;

use Desktopd\PlatformTools\Log;


/*
    Autoloader
*/
spl_autoload_register(function ($class) {
    if (class_exists($class, false)) {
        return;
    }
    
    $name = strtr("$class", '\\', '/');
    if (!preg_match('~^[_a-zA-Z][_a-zA-Z0-9]*(?:/[_a-zA-Z][_a-zA-Z0-9]*)*$~', $name)) {
        return;
    }
    
    $path = dirname(dirname(__DIR__)) . "/classes/{$name}.php";
    if (is_file($path) && is_readable($path)) {
        require_once $path;
    }
    
}, true, true);


/*
    Listing pictures
*/
header('Content-Type: application/json;  charset=UTF-8');

try {
    $selfURI = $_SERVER['SCRIPT_NAME'];
    $pictureDir = new PictureServer\PictureDirectory(__DIR__ . '/pictures');
    
    $selfName = basename(__FILE__);
    
    // remove filename
    if (substr($selfURI, -strlen($selfName)) !== $selfName) {
        // ERROR: Unknown condition
        throw new \RuntimeException("Could not get the path");
        
    }
    
    // __DIR__ seen from client (empty if docroot)
    $basePath = substr($selfURI, 0, -1 - strlen($selfName));
    
    $pictures = array();
    foreach ($pictureDir as $picturePath) {
        $pictures[] = "$basePath/pictures/$picturePath";
    }
    
    $flags = 0;
    if (defined('JSON_UNESCAPED_SLASHES')) {
        $flags |= JSON_UNESCAPED_SLASHES;
    }
    echo json_encode($pictures, $flags);
    
} catch (\Exception $e) {
    Log::log("$selfURI: Exception: $e", Log::ERROR);
    echo "[]";
}

exit; // Intentional explicit EXIT


// vim: ts=4 et ai

